<?php


namespace app\api\service\order;


use app\api\model\MemberOrder;
use app\api\model\MemberType;
use app\api\service\Token;
use app\lib\exception\ParameterException;

/**
 * 1. 会员卡信息判断
 * 2. 创建会员卡支付信息
 * 3. 判断订单价格
 * 4. 为零修改订单状态
 * 5. 返回支付number与支付成功状态
 */

class CreateMemberTypeOrder extends Token
{
    /**
     * 会员卡信息
     */
    protected $memberType;

    /**
     * 会员信息
     */
    protected $user;

    function __construct($id){
        $this->memberType = MemberType::get($id);
    }

    /**
     * 入口方法
     */
    public function entrance()
    {
        return $this->judgeMemberType();
    }

    /**
     * 判断会员卡信息
     */
    protected function judgeMemberType()
    {
        $this->user = self::judgeUser();
        if(!$this->memberType) {
            throw new ParameterException([
                'msg' => [
                    'member_type_order' => '会员卡信息错误'
                ]
            ]);
        }
        return $this->createOrder();
    }

    /**
     * 创建会员卡支付信息
     */
    protected function createOrder()
    {
        $mode = MemberOrder::create([
            'openid' => $this->user['openid'],
            'member_type_id' => $this->memberType['id'],
            'price' => $this->memberType['money'],
            'member_type_msg' => json_encode($this->memberType),
            'look_num' => $this->memberType['look_num'],
            'member_type_name' => $this->memberType['name'],
        ]);
        $mode->out_trade_no = '1t2021'.$mode->id;
        $mode->save();
        return [
            'out_trade_no' => '1t2021'.$mode->id
        ];
    }
}